package com.junt.library.core;

import android.app.Application;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;

import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Log;

import com.junt.library.MediaSelector;
import com.junt.library.interfaces.QueryListener;
import com.junt.library.model.Media;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 异步查询
 */
public class QueryTask extends AsyncTask<String, Integer, List<Media>> {

    private Application application;
    private QueryListener listener;

    public QueryTask(Application application, QueryListener listener) {
        this.application = application;
        this.listener = listener;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        listener.onStart();
    }

    @Override
    protected List<Media> doInBackground(String... s) {
        List<Media> mediaList = new ArrayList<>();
        ContentResolver resolver = application.getContentResolver();
        QueryParam queryParam = new QueryParam();
        try {
            Cursor cursor = resolver.query(
                    //这里决定查询的媒体类型
                    queryParam.getContentUri(),
                    null,
                    queryParam.getSelection(),
                    null,
                    queryParam.getSortOrder(false));
            String[] cursorColumnNames = cursor.getColumnNames();
//            Log.i("MediaSelector", "doInBackground: columns[]="+Arrays.toString(cursorColumnNames));
            List<String> columnNames = Arrays.asList(cursorColumnNames);
            // 缓存column Id
            int idColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID);
            int nameColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
            int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.SIZE);
            int absolutePathColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            int dateAddedColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_ADDED);
            int dateModifiedColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_MODIFIED);
            int mimeTypeColumn = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.MIME_TYPE);
            int widthColumn = -1;
            if (columnNames.contains(MediaStore.Images.ImageColumns.WIDTH)) {
                widthColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.WIDTH);
            }
            int heightColumn = -1;
            if (columnNames.contains(MediaStore.Images.ImageColumns.HEIGHT)) {
                heightColumn = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.HEIGHT);
            }
            int resolutionColumn=-1;
            if (columnNames.contains(MediaStore.Video.VideoColumns.RESOLUTION)) {
                resolutionColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.VideoColumns.RESOLUTION);
            }
            int durationColumn = -1;
            if (columnNames.contains("duration")) {
                durationColumn = cursor.getColumnIndexOrThrow("duration");
            }
            int orientationColumn = -1;
            if (columnNames.contains("orientation")) {
                orientationColumn = cursor.getColumnIndexOrThrow("orientation");
            }
            int relativePathColumn = -1;
            if (columnNames.contains("relative_path")) {
                relativePathColumn = cursor.getColumnIndexOrThrow("relative_path");
            }

            //数据库遍历
            while (cursor.moveToNext()) {
                long id = cursor.getLong(idColumn);
                String name = cursor.getString(nameColumn);
                long size = cursor.getLong(sizeColumn);
                String mimeType = cursor.getString(mimeTypeColumn);
                long dateAdded=cursor.getLong(dateAddedColumn);
                long dateModified = cursor.getLong(dateModifiedColumn);
                String absolutePath = cursor.getString(absolutePathColumn);
                long duration = 0;
                if (durationColumn >= 0) {
                    duration = cursor.getInt(durationColumn);
                }
                int orientation = 0;
                if (orientationColumn >= 0) {
                    orientation = cursor.getInt(orientationColumn);
                }
                int width = 0;
                if (widthColumn >= 0) {
                    width = cursor.getInt(widthColumn);
                }
                int height = 0;
                if (widthColumn >= 0) {
                    height = cursor.getInt(heightColumn);
                }
                String resolution = "0x0";
                if (resolutionColumn >= 0) {
                    resolution = cursor.getString(resolutionColumn);
                }
                String relativePath = "";
                if (relativePathColumn >= 0) {
                    relativePath = cursor.getString(relativePathColumn);
                }

                Uri contentUri = ContentUris.withAppendedId(queryParam.getContentUri(), id);

                Media media = new Media(
                        contentUri,
                        name,
                        size,
                        duration,
                        dateModified,
                        dateAdded,
                        mimeType, orientation,
                        width, height,resolution,
                        relativePath, absolutePath);

                mediaList.add(media);
                listener.onNext(media);
            }
            cursor.close();
        } catch (Exception e) {
            listener.onError(e);
        }
        return mediaList;
    }

    @Override
    protected void onPostExecute(List<Media> medias) {
        super.onPostExecute(medias);
        if (medias == null || medias.size() == 0) {
            listener.onError(new Exception("MediaSelector: No media file has been discovered!"));
        } else {
            listener.onComplete(medias);
        }
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        listener = null;
    }


}
